//
//  Tool.m
//  tangkerU
//
//  Created by yanzhen on 14-5-1.
//  Copyright (c) 2014年 yanzhen. All rights reserved.
//

#import "Tool.h"
#import <math.h>
#import "Config.h"
#import "SBJsonParser.h"
#import "JsonUtil.h"


@implementation Tool

+(void) showHUD:(NSString *)text andView:(UIView *)view andHUD:(MBProgressHUD *)hud
{
    [view addSubview:hud];
    hud.labelText = text;
    //    hud.dimBackground = YES;
    hud.square = YES;
    [hud show:YES];
}
+(NSString*) appendString:(NSString *)str1 with:(NSString *)str2
{
    NSString *str =[[NSString alloc] initWithFormat:@"%@%@",str1,str2];
    return str;
}


+ (NSString *)getOSVersion
{
    return [NSString stringWithFormat:@"yanzhen.com /%@/%@/%@/%@",@"1.0.0",[UIDevice currentDevice].systemName,[UIDevice currentDevice].systemVersion, [UIDevice currentDevice].model];
}

+(NSString *)dateFormat:(NSDate*)date
{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//设定时间格式
    
    NSString *dateString = [dateFormat stringFromDate:date]; //求出当天的时间字符串，当更改时间格式时，时间字符串也能随之改变
    return dateString;
}

+(NSString *)dateLocalPrint:(NSString *)sendTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    
    NSDate * date = [formatter dateFromString:sendTime];
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    //debugLog(@"localTimeZone is %@",localTimeZone);

    NSDate * today = [NSDate date];
    NSDate * yesterday = [NSDate dateWithTimeIntervalSinceNow:-86400];
    NSDate * refDate = date;

    NSString * todayString = [[today description] substringToIndex:10];
    NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    NSString * refDateString = [[date description] substringToIndex:10];
     
    if ([refDateString isEqualToString:todayString])
    {
         [formatter setDateFormat:@"HH:mm"];
         NSString *format_txt = [formatter stringFromDate:date];
         return [NSString stringWithFormat:@"%@",format_txt];
    } else if ([refDateString isEqualToString:yesterdayString])
    {
        [formatter setDateFormat:@"HH:mm"];
        NSString *format_txt = [formatter stringFromDate:date];
        return [NSString stringWithFormat:@"昨天 %@",format_txt];
    }
    else
    {
        return [formatter stringFromDate:date];
    }
}

+(NSString *) getAnimal:(NSInteger)animal
{
    
    NSArray *animals = @[@"鼠", @"牛", @"虎", @"兔", @"龙", @"蛇", @"马", @"羊", @"猴", @"鸡", @"狗", @"猪"];
    NSString * animalStr = [animals objectAtIndex:animal];
    return animalStr;
}

+(NSString *)getConstellatory:(NSInteger)constellatory
{
    NSArray *constellatorys = @[@"白羊座",@"金牛座", @"双子座",@"巨蟹座",@"狮子座",@"处女座", @"天秤座",@"天蝎座",@"射手座",@"摩羯座",@"水瓶座",@"双鱼座"];
    return [constellatorys objectAtIndex:constellatory];
}

+(NSString *)getMarry:(NSInteger)marry
{
    NSArray *marrys = @[@"保密",@"单身",@"已婚",@"离异"];
    return [marrys objectAtIndex:marry];
}

+(NSString*)getSex:(NSInteger)sex
{
    NSArray *sexs = @[@" ",@"男", @"女"];
    return [sexs objectAtIndex:sex];
}

+(void) setLayerView:(UIImageView *) photo_img
{
    SLLogRect([photo_img bounds]);
    [photo_img.layer setCornerRadius:CGRectGetHeight([photo_img bounds]) / 2];
    photo_img.layer.masksToBounds = YES;
    photo_img.layer.borderWidth = 1;
    photo_img.layer.borderColor = [[UIColor whiteColor] CGColor];
    
}
+(void) setLayerView:(UIImageView *) photo_img andBound:(CGRect)bounds
{
    
    [photo_img.layer setCornerRadius:CGRectGetHeight(bounds) / 2];
    photo_img.layer.masksToBounds = YES;
    photo_img.layer.borderWidth = 1;
    photo_img.layer.borderColor = [[UIColor whiteColor] CGColor];
    
}
+(void)showSystemAlert:(NSString *)title andMsg:(NSString *)msg
{
    if(title == nil){
        title = @"提示";
    }
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

+(void)reSetInfo
{
    NSString * url = [NSString stringWithFormat:@"%@%@/uid/%d",SERVER_URL_NEW,kMyInfomartion,[Config Instance].getUID];
    [[AFAppClient sharedManager]getWithURL:url withParameters:nil success:^(NSDictionary *responseObject) {
        
        NSInteger code = [[responseObject objectForKey:@"code"] integerValue];
        if(code){
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            NSDictionary *resultInfo = [responseObject objectForKey:@"result"];
            [defaults setObject:[JsonUtil convertDictionaryToJson:resultInfo] forKey:@"info"];
            [[EaseMob sharedInstance].chatManager setApnsNickname:[resultInfo objectForKey:@"nickname"]];
            [[NSNotificationCenter defaultCenter] postNotificationName:kReloadInfo object:@YES];
        }else{
            
        }

    } failure:^(NSError *error) {
        
    }];
}

+(NSDictionary*)getInfoById:(NSString *)uid
{
     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *info_str = [defaults objectForKey:[NSString stringWithFormat:@"info_%@",uid]];
    if(info_str&&[info_str length]>0){
        SBJsonParser *parser = [SBJsonParser new];
        NSDictionary *info = [parser objectWithString:info_str];
        return info;
    }else{
   
    NSString * url = [NSString stringWithFormat:@"%@%@/uid/%@",SERVER_URL_NEW,kMyInfomartion,uid];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]
                                         options:NSDataReadingMappedIfSafe
                                           error:nil];
    if (data) {
        NSDictionary *userInfoDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSDictionary *infoDic = [userInfoDic objectForKey:@"result"];
        [defaults setObject:[JsonUtil convertDictionaryToJson:infoDic] forKey:[NSString stringWithFormat:@"info_%@",uid]];
        return infoDic;
    }else{
        return nil;
        }
    }
}

+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])[0-9]{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])[0-9])[0-9]{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])[0-9]{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)[0-9]{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\\\d{3})\\\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
  //  BOOL result = [regextestcu evaluateWithObject:mobileNum];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+(BOOL)checkAuth
{
    if([Config Instance].isCookie &&([[Config Instance]getUID]>0)){
            return YES;
    }else{
        [Tool showSystemAlert:@"无权限" andMsg:@"对不起，您需要登录才能继续~"];
        return NO;
    }
}
+(BOOL)checkVip
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSUInteger is_vip = [[defaults objectForKey:@"is_vip"]integerValue];
    if(is_vip>0){
        return YES;
    }else{
        [Tool showSystemAlert:@"无权限" andMsg:@"对不起，您需要VIP权限才能继续~"];
        return NO;
    }
}
+(NSDictionary*)getMyInfo
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *myInfo = @"";

    myInfo= [defaults objectForKey:@"info"];
    
    
    SBJsonParser *parser = [[SBJsonParser alloc]init];
    NSDictionary *infoDic = [parser objectWithString:myInfo];
    NSInteger code = [[infoDic objectForKey:@"code"] integerValue];
    if(code){
        NSDictionary *result = [infoDic objectForKey:@"result"];
        return result;
    }else{
        return nil;
    }
}
+(NSDictionary*)getInfoWith:(NSUInteger)uid
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *myInfo = @"";
    
    myInfo= [defaults objectForKey:[NSString stringWithFormat:@"info_%d",uid]];
    
    SBJsonParser *parser = [[SBJsonParser alloc]init];
    NSDictionary *infoDic = [parser objectWithString:myInfo];
    NSInteger code = [[infoDic objectForKey:@"code"] integerValue];
    if(code){
        NSDictionary *result = [infoDic objectForKey:@"result"];
        return result;
    }else{
        return nil;
    }
}

+(NSString*)formatGold:(NSUInteger)gold
{
    if(gold<100000){
        return [NSString stringWithFormat:@"%d",gold];
    }else if(gold<100000000){
        NSUInteger wan  = gold/10000;
        return [NSString stringWithFormat:@"%d万",wan];
    }else{
        NSUInteger wan  = gold/100000000;
        return [NSString stringWithFormat:@"%d亿",wan];
    }
}
+(NSString *)getTags:(NSString*)tags withSex:(NSUInteger)sex
{
    NSArray *arr = [tags componentsSeparatedByString:@","];
    NSString *tag_label = @"";
    if([arr count]>0){
        for (NSString *value in arr) {
            NSUInteger va = [value integerValue];
            NSString *label = @"";
            if(sex == 1){
                switch (va) {
                    case 1:
                        label=@"帅气俊逸";
                        break;
                    case 2:
                        label=@"性感魅惑";
                        break;
                    case 3:
                        label=@"成熟大方";
                        break;
                    case 4:
                        label=@"健康阳光";
                        break;
                    case 5:
                        label=@"成熟体贴";
                        break;
                    default:
                        break;
                }
            }else{
                switch (va) {
                    case 1:
                        label=@"气质优雅";
                        break;
                    case 2:
                        label=@"娇小可爱";
                        break;
                    case 3:
                        label=@"成熟大方";
                        break;
                    case 4:
                        label=@"性感娇柔";
                        break;
                    case 5:
                        label=@"忧郁魅惑";
                        break;
                    default:
                        break;
                }
            }
            tag_label = [NSString stringWithFormat:@"%@ %@",tag_label,label];
        }
    }
    return tag_label;
}
+(UIViewController*)getViewController:(NSString *)identify withBund:(NSString*)bundle
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:bundle bundle:nil];
    UIViewController *controller = [storyboard instantiateViewControllerWithIdentifier:identify];
    return controller;
}

+ (UIImage *)convertImageToGrayScale:(UIImage *)image
{
  // Create image rectangle with current image width/height
  CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);

  // Grayscale color space
  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

  // Create bitmap content with current image size and grayscale colorspace
  CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);

  // Draw image into current context, with specified rectangle
  // using previously defined context (with grayscale colorspace)
  CGContextDrawImage(context, imageRect, [image CGImage]);

  // Create bitmap image info from pixel data in current context
  CGImageRef imageRef = CGBitmapContextCreateImage(context);

  // Create a new UIImage object  
  UIImage *newImage = [UIImage imageWithCGImage:imageRef];

  // Release colorspace, context and bitmap information
  CGColorSpaceRelease(colorSpace);
  CGContextRelease(context);
  CFRelease(imageRef);

  // Return the new grayscale image
  return newImage;
}

+ (NSString*) stringFromFomate:(NSDate*) date formate:(NSString*)formate {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formate];
    
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    [formatter setTimeZone:timeZone];
    
    NSString *str = [formatter stringFromDate:date];
    return str;
}

+ (NSString *)intervalSinceNow:(NSString *) theDate {
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"MM/dd/yyyy HH:mm"];
    NSDate *d=[date dateFromString:theDate];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=now-late;
    if (cha/3600<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        timeString = [timeString substringToIndex:timeString.length-7];
        if ([timeString isEqualToString:@"0"]) {
            timeString = @"刚刚更新";
        }else
        {
            timeString=[NSString stringWithFormat:@"%@分钟前", timeString];
        }
    }
    if (cha/3600>1&&cha/86400<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@小时前", timeString];
    }
    if (cha/86400>1)
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@天前", timeString];
        
    }
    return timeString;
}

+ (NSMutableDictionary *)readFromePath:(NSString *)paths
{
    NSString *path = [HomeDirectory stringByAppendingString:paths];
    
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:path] ? [[NSMutableDictionary alloc] initWithContentsOfFile:path] : [[NSMutableDictionary alloc] init];
    return data;
}

+ (NSMutableArray *)readArrayFromePath:(NSString *)paths
{
    NSString *path = [HomeDirectory stringByAppendingString:paths];
    
    NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path] ? [[NSMutableArray alloc] initWithContentsOfFile:path] : [[NSMutableArray alloc] init];
    return data;
}

+ (void)writeArrayToPlist:(NSString *)plist array:(NSMutableArray *)array
{
    NSString *user_path = [HomeDirectory stringByAppendingString:plist];
    [array writeToFile:user_path atomically:YES];
}

+ (void)writeDictToPlist:(NSString *)plist dict:(NSDictionary *)dict
{
    NSString *user_path = [HomeDirectory stringByAppendingString:plist];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dict];
    [params writeToFile:user_path atomically:YES];
}

+ (NSString *)today
{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [dateFormatter setTimeZone:timeZone];
    return [dateFormatter stringFromDate:[NSDate date]];
}

+ (NSString *)fullDate
{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [dateFormatter setTimeZone:timeZone];
    return [dateFormatter stringFromDate:[NSDate date]];
}

+ (NSString *)dateCutHour:(NSString *)time
{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"];
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [dateFormatter setTimeZone:timeZone];
    
    NSDate *date = [dateFormatter dateFromString:time];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    return [dateFormatter stringFromDate:date];
}
+ (NSString *)timeStamp
{
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
    return timeSp;
}
+ (NSString *)nowDate
{
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
    return timeSp;
}

+ (NSString *)timeToStamp:(NSString *)timeStr
{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [dateFormatter setTimeZone:timeZone];
    
    NSDate* date = [dateFormatter dateFromString:timeStr];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    return timeSp;
}
+(BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+(NSString*) defaultStringFromDic:(NSDictionary *)dic withKey:(NSString *)key
{
    if([NSNull null] == [dic objectForKey:key]){
        return @"";
    }else{
        return [dic objectForKey:key];
    }
}
+(NSInteger) defaultIntFromDic:(NSDictionary *)dic withKey:(NSString *)key
{
    if([NSNull null] == [dic objectForKey:key]){
        return 0;
    }else{
        return [[dic objectForKey:key] intValue];
    }
}

@end
